import { useState } from "react";
import { useAtomValue } from "jotai";
import { useNavigate } from "react-router";
import { Button, Input, Select, Table } from "antd";
import { DetailDialog } from "./DetailDialog";
import EditOrderDialog from "./EditOrderDialog";
import SearchIcon from "@/assets/icons/search.svg?jsx";
import AddIcon from "@/assets/images/add.png?jsx";
import PlayIcon from "@/assets/images/play-button1.png?jsx";
import EditIcon from "@/assets/images/edit-text.png?jsx";
import useFetch from "@/lib/hooks/useFetch";
import { getOrderList, runOrder } from "@/lib/api/order";
import { tokenAtom } from "@/store/user";
import useOnMounted from "@/lib/hooks/useOnMounted";
import { useMessage } from "@/providers/AntdMessageProvider";
import getRequestErrorMessage from "@/lib/utils/getRequestErrorMessage";
import type { IOrder } from "@/lib/types";

const Status = ["未开始", "已开始", "暂停中", "已结束"];

export default function Order() {
  const [searchData, setSearchData] = useState({
    order: "",
    status: undefined,
  });
  const [detailDialog, setDetailDialog] = useState({
    visible: false,
  });
  const [editDialog, setEditDialog] = useState({
    visible: false,
    target: null as IOrder | null,
  });
  const [pagination, setPagination] = useState({
    index: 1,
    size: 10,
    total: 0,
  });

  const token = useAtomValue(tokenAtom);
  const message = useMessage();

  const {
    isLoading: isOrderDataLoading,
    data: orderData,
    refetch: loadOrderList,
  } = useFetch({
    fetchFn: (data: Parameters<typeof getOrderList>[0], signal: AbortSignal) =>
      getOrderList(data, token, signal).then((res) => {
        if (res.code !== 200) {
          throw res;
        }
        setPagination((p) => ({ ...p, total: res.total }));
        return res.rows;
      }),
    onError(error) {
      message.error(getRequestErrorMessage(error));
    },
  });

  function handleLoadOrderList(
    index = pagination.index,
    size = pagination.size,
  ) {
    if (index !== pagination.index || size !== pagination.size) {
      setPagination((p) => ({ ...p, index, size }));
    }
    loadOrderList({
      pageNum: index,
      pageSize: size,
      orderNo: searchData.order,
      orderStatus: searchData.status,
    });
  }

  useOnMounted(() => {
    handleLoadOrderList();
  });

  return (
    <>
      <div className="relative flex h-full flex-col px-10 pt-12">
        <div className="flex flex-none gap-x-4">
          <Input
            value={searchData.order}
            onInput={(e) =>
              setSearchData((p) => ({
                ...p,
                order: (e.target as HTMLInputElement).value,
              }))
            }
            placeholder="委托单号"
            style={{ width: 300 }}
          />
          <div>
            <span>实验状态&nbsp;</span>
            <Select
              placeholder="选择实验状态"
              value={searchData.status}
              onChange={(v) => setSearchData((p) => ({ ...p, status: v }))}
              style={{ width: 150 }}
              options={Status.map((label, value) => ({ label, value }))}
            />
          </div>
          <Button onClick={() => handleLoadOrderList(1)}>
            <SearchIcon />
          </Button>
          <Button
            className="ml-auto"
            onClick={() => setEditDialog({ visible: true, target: null })}
          >
            <AddIcon className="size-4" />
            添加
          </Button>
        </div>
        <div className="mt-8 min-h-0 flex-auto overflow-auto">
          <Table
            loading={isOrderDataLoading}
            dataSource={orderData || []}
            rowKey={(row) => row.orderId}
            pagination={{
              onChange(page, pageSize) {
                handleLoadOrderList(page, pageSize);
              },
            }}
          >
            <Table.Column title="委托单号" dataIndex="orderNo" />
            <Table.Column title="型号" dataIndex="modelNo" />
            <Table.Column title="名称" dataIndex="modelName" />
            <Table.Column title="实验项目" dataIndex="experimentItem" />
            <Table.Column title="开始时间" dataIndex="startTime" />
            <Table.Column title="结束时间" dataIndex="endTime" />
            <Table.Column title="设备" dataIndex="deviceName" />
            <Table.Column
              title="状态"
              render={(row) => Status[row.orderStatus]}
            />
            <Table.Column
              render={(row) => (
                <OrderControl
                  order={row}
                  onEdit={(order) =>
                    setEditDialog({ visible: true, target: order })
                  }
                  onRunSuccess={() => {}}
                />
              )}
            />
          </Table>
        </div>
      </div>
      <DetailDialog
        visible={detailDialog.visible}
        onVisibleChange={(visible) => setDetailDialog({ visible })}
      />
      <EditOrderDialog
        visible={editDialog.visible}
        target={editDialog.target}
        onClose={() => setEditDialog({ visible: false, target: null })}
        onSuccess={handleLoadOrderList}
      />
    </>
  );
}

type RunOrderControlProps = {
  order: IOrder;
  onRunSuccess: () => void;
  onEdit: (order: IOrder) => void;
};

function OrderControl(props: RunOrderControlProps) {
  const { order, onEdit } = props;

  const token = useAtomValue(tokenAtom);
  const message = useMessage();
  const navigate = useNavigate();

  const { isLoading: isRunLoading, refetch: _runOrder } = useFetch({
    fetchFn: () =>
      runOrder(order.orderId, token).then((res) => {
        if (res.code !== 200) {
          throw res;
        }
      }),
    onError(error) {
      message.error(getRequestErrorMessage(error));
    },
    onSuccess() {
      message.success("操作成功！");
      navigate(`/dashboard/${order.deviceId}`);
    },
  });

  return (
    <div className="flex gap-x-2">
      <Button onClick={() => onEdit(order)}>
        <EditIcon className="size-3" />
        编辑
      </Button>
      <Button loading={isRunLoading} onClick={_runOrder}>
        <PlayIcon className="size-3" />
        运行
      </Button>
    </div>
  );
}
